package cn.geminis.manage.service.controller;

import cn.geminis.core.data.query.QueryParameters;
import cn.geminis.manage.core.entity.Config;
import cn.geminis.manage.service.model.ConfigRepository;
import cn.geminis.web.logging.LoggingMethod;
import cn.geminis.web.logging.LoggingParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Allen
 */
@RestController
@RequestMapping("/configs")
public class ConfigController {

    @Autowired
    private ConfigRepository repository;

    @PostMapping
    public Page<Config> findPage(@RequestBody final QueryParameters queryParameters) {
        return this.repository.findPage(queryParameters);
    }

    @GetMapping("/{id}")
    public Config get(@PathVariable String id, String defaultValue) {
        return this.repository.findById(id).orElseGet(() ->
                {
                    var config = new Config();
                    config.setId(id);
                    config.setValue(defaultValue);
                    this.repository.save(config);
                    return config;
                }
        );
    }

    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("hasAuthority('manage')")
    @LoggingMethod("设置配置")
    public void save(@RequestBody @LoggingParam(value = "配置ID", field = "id") List<Config> configs) {
        this.repository.saveAll(configs::iterator);
    }
}
